/**
 * 
 */
package cankaoxiaoxi;

import java.io.FileNotFoundException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import util.StrUtil;

import com.wixc.entity.NewBean;
import com.wixc.util.ConstantsUtil;
import com.wixc.util.JdbcUtils;
import com.wixc.util.LoginUtil;


/**
 * @author weichuanxi
 * @date 2016年3月17日
 */
public class CanKaoXiaoXi_HotNews {
	static ArrayList<NewBean> list = new ArrayList<NewBean>();

	/**
	 * @param args
	 * @throws FileNotFoundException
	 * @throws SQLException
	 */
	public static void main(String[] args) throws FileNotFoundException, SQLException {
		
		CanKaoXaioXi_HotNews_Run();
	}
	public static void CanKaoXaioXi_HotNews_Run(){
		LoginUtil util = new LoginUtil();
		String html = util.Get("http://www.cankaoxiaoxi.com/");
		try {
			processor(util, html);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			JdbcUtils.saveNews(list, "insert into news (id, title, detail, source, imageUrl,typeid,insertTime) values (?,?, ?,?,?,?, ?)");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private static ArrayList<NewBean> processor(LoginUtil util, String html) throws FileNotFoundException, SQLException {

		Document doc = Jsoup.parse(html);
		Elements hotNews = doc.select("div.main_right.f-l.mar-l-20.sens > div.hot.ov > h1");
		return deal(util, hotNews, ConstantsUtil.hotNews);
	}

	private static ArrayList<NewBean> deal(LoginUtil util, Elements e, int typeid) throws SQLException {

		for (Element element : e) {
			// url title
			String url = element.select("a").attr("href");
			String name = element.text();

			String html = util.Get(url);
			Document doc = Jsoup.parse(html);
			// detail
			String detail = doc.select("#ctrlfscont").outerHtml();
			Elements imgurls=doc.select("#ctrlfscont").select("img");
			String imgurl=StrUtil.imgUrls("", imgurls);
			// 分页
			Elements ul = doc.select("div.bg-content > div.inner > div.page.center.mar-b-10").select("ul>li");
			if (ul.size() > 0) {
				ul.remove(ul.size() - 1);
				ul.remove(0);
				ul.remove(0);
				for (Element element2 : ul) {
					String nexturl = element2.select("a").attr("href");
					String nhtml = util.Get(nexturl);
					Document ndoc = Jsoup.parse(nhtml);
					String ndetail = ndoc.select("#ctrlfscont").outerHtml();
					detail += "<hr/>" + ndetail;
				}
			}

			NewBean news = new NewBean(0, name, detail.replace("点击图片进入下一页", ""), "参考消息", imgurl, typeid, new Date(System.currentTimeMillis()));
			list.add(news);
		}
		return list;
	}

}
